// 对传输线的接口进行整理
const service = require("../../utils/request");
const uuid = require("uuid");
const { getProductionByPalletCode } = require("../../utils/getProduction");
const logger = require("../../utils/loggers");
const {
  chengpinShuSongUrl,
  chengpinLoginData,
  loginRouterApi,
  freeLineApi,
  snResultApi,
  feedbackresultApi,
  wcsUrl,
  wcsSnAllPalletizingApi,
  wcsData,
} = require("../../utils/config");
const { response } = require("express");

// 常量定义
const MAX_RETRY_TIMES = 3;
const RETRY_INTERVAL = 500;

/**
 * 传输线登录
 * @param {Object} data - 登录数据
 * @returns {Promise} 请求结果
 */
const loginCreateToken = (data) => {
  logger.info(`登录的url地址${chengpinShuSongUrl}${loginRouterApi}`);
  return service({
    url: chengpinShuSongUrl + loginRouterApi,
    method: "post",
    data,
  });
};

/**
 * 码垛线空闲状态更新
 * @param {Object} data - 请求数据
 * @returns {Promise} 请求结果
 */
const freeLineHandle = (data) => {
  logger.info(
    `码垛线空闲状态更新url地址${chengpinShuSongUrl}${loginRouterApi}`
  );
  logger.info(
    `码垛线空闲状态更新的url地址${
      chengpinShuSongUrl + freeLineApi
    },传递的参数${JSON.stringify(data)}`
  );
  return service({
    url: chengpinShuSongUrl + freeLineApi,
    method: "post",
    data,
  });
};

/**
 * 传输线单个码垛线状态反馈
 * @param {Object} data - 请求数据
 * @returns {Promise} 请求结果
 */
const snresultHandle = (data) => {
  logger.info(`传输线单个码垛线状态反馈,传参${JSON.stringify(data)}`);
  return service({
    url: chengpinShuSongUrl + snResultApi,
    method: "post",
    data,
  });
};

/**
 * 传输线整体码垛线状态反馈
 * @param {Object} data - 请求数据
 * @returns {Promise} 请求结果
 */
const csxfeedbackresultHandle = (data) => {
  logger.info(`传输线整体码垛线状态反馈,传参${JSON.stringify(data)}`);
  logger.info(
    `传输线整体码垛线状态反馈的url 地址${chengpinShuSongUrl}${feedbackresultApi}`
  );
  return service({
    url: chengpinShuSongUrl + feedbackresultApi,
    method: "post",
    data,
  });
};

/**
 * 重试操作
 * @param {Function} operation - 要执行的操作
 * @param {number} maxRetries - 最大重试次数
 * @returns {Promise<any>} 操作结果
 */
async function retryOperation(operation, maxRetries) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await operation();
    } catch (err) {
      console.error(`操作失败 (尝试 ${attempt}/${maxRetries}):`, err.message);
      if (attempt < maxRetries) {
        logger.warn(`操作失败，等待后重试...`);
        await new Promise((resolve) =>
          setTimeout(resolve, RETRY_INTERVAL * attempt)
        );
      }
    }
  }
  return false;
}

/**
 * 空闲状态更新
 * @param {Object} req - 请求对象
 * @param {Object} proData - 产品数据
 */
async function csxFree(req, proData) {
  try {
    if (!req || !req.headers || !proData) {
      console.error("csxFree: 参数无效", { req, proData });
      return;
    }

    // 优先从 session 获取 accepttoken，如果没有则从 headers 获取
    const accepttoken =
      (req.session && req.session.AcceptToken) || req.headers.accepttoken;

    if (!accepttoken) {
      logger.warn("缺少 accepttoken");
      return;
    }

    const payload = {
      palletizingCode: `${proData.beUsed}${proData.lineName}`,
      acceptToken: accepttoken,
    };

    await retryOperation(async () => {
      const response = await freeLineHandle(payload);
      logger.info(`freeLineHandle 成功,${JSON.stringify(response)}`);
      return true;
    }, MAX_RETRY_TIMES);
  } catch (error) {
    logger.info(`空闲状态更新失败 :${error.message}`);
  }
}

/**
 * 单个码垛线完成反馈
 * @param {Object} req - 请求对象
 * @param {string} sn - 产品序列号
 */
async function csxOneFinish(req, sn) {
  try {
    if (!req || !req.headers || !sn) {
      console.error("csxOneFinish: 参数无效", { req, sn });
      return;
    }

    // 优先从 session 获取 accepttoken，如果没有则从 headers 获取
    const accepttoken =
      (req.session && req.session.AcceptToken) || req.headers.accepttoken;

    if (!accepttoken) {
      logger.warn("缺少 accepttoken");
      return;
    }

    const payload = {
      sn,
      acceptToken: accepttoken,
    };

    await retryOperation(async () => {
      const response = await snresultHandle(payload);
      logger.info(`单个码垛结果反馈成功,${JSON.stringify(response)}`);
      return true;
    }, MAX_RETRY_TIMES);

    logger.info("单个码垛线完成反馈完成");
  } catch (error) {
    logger.info(`单个码垛线完成反馈失败${error.message} `);
  }
}

/**
 * 传输线整体码垛完成处理
 * @param {Object} req - 请求对象
 * @param {string} palletCode - 托盘编号
 */
async function csxFinishAll(req, palletCode) {
  try {
    if (!req || !req.headers || !palletCode) {
      console.error("csxFinishAll: 参数无效", { req, palletCode });
      return;
    }

    // 优先从 session 获取 accepttoken，如果没有则从 headers 获取
    const accepttoken =
      (req.session && req.session.AcceptToken) || req.headers.accepttoken;
    logger.info(`传输线整体码垛线完成的accepttoken::${accepttoken}`);

    if (!accepttoken) {
      logger.warn("缺少 accepttoken");
      return;
    }

    const snDataList = await getProductionByPalletCode(palletCode);

    if (!snDataList || snDataList.length === 0) {
      logger.info(`未找到对应的产品数据 `);
      return;
    }

    logger.info(`snDataList:${JSON.stringify(snDataList)} `);
    let palletData = [];
    for (let i = 0; i < snDataList.length; i++) {
      let item = snDataList[i];
      let obj = {
        sn: item.sn,
        productCode: item.productCode,
        sono: item.sono,
        soline: item.soline,
        length: item.long,
        width: item.wide,
        height: item.height,
        weight: item.weight,
      };
      logger.info(`obj:${JSON.stringify(obj)}`);
      palletData.push(obj);
    }

    // 构造请求参数
    const feedbackresultParams = {
      palletCode,
      amount: palletData.length,
      palletData: palletData,
      acceptToken: accepttoken,
    };

    logger.info(`传输线整体码垛参数${JSON.stringify(feedbackresultParams)}`);

    await retryOperation(() => {
      return new Promise((resolve, reject) => {
        csxfeedbackresultHandle(feedbackresultParams)
          .then((response) => {
            logger.info(`整垛结果反馈成功${JSON.stringify(response)}`);
            logger.info(
              `csxfeedbackresultHandle 成功,${JSON.stringify(response)}`
            );
            resolve(true);
          })
          .catch((error) => {
            logger.error(`csxfeedbackresultHandle 失败: ${error.message}`, {
              error: error.stack || error,
              params: feedbackresultParams,
            });
            reject(error);
          });
      });
    }, MAX_RETRY_TIMES);
  } catch (error) {
    console.error(
      `传输线整体码垛完成失败${JSON.stringify(error)},错误信息是：${
        error.message
      }`
    );
  }
}

module.exports = {
  loginCreateToken,
  csxFree,
  snresultHandle,
  csxOneFinish,
  csxFinishAll,
};
